package com.wanmait.recruitment.Filter;





import com.wanmait.recruitment.pojo.Company;
import com.wanmait.recruitment.pojo.Userinfo;
import com.wanmait.recruitment.service.UserinfoService;
import com.wanmait.recruitment.util.CookieUtil;
import com.wanmait.recruitment.util.MD5Util;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class UserinfoAutoLoginFilter implements Filter {

    @Resource
    private UserinfoService userinfoService;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        HttpSession session = request.getSession();
        Userinfo user = (Userinfo) session.getAttribute("userinfo");
        Company company = (Company) session.getAttribute("company");
        //如果已经登录了放行
        if(user!=null&&company!=null)
        {
            chain.doFilter(req, resp);
            return;
        }

        //读取cookie
        String email = CookieUtil.getValue("email",request);
        String password = CookieUtil.getValue("password", request);
        if(email==null || password==null)
        {
            chain.doFilter(req, resp);
            return;
        }
        user = userinfoService.findByUsername(email);
        if (user!=null) {
            if (password.equals(MD5Util.myMD5(user.getUserpass()))) {
                session.setAttribute("userinfo", user);
                //重写cookie
                int maxAge = 60 * 60 * 24 * 30;
                CookieUtil.addCookie("email", email, "/", maxAge, response);
                CookieUtil.addCookie("password", password, "/", maxAge, response);
            }
        }
        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {

    }

}
